package myself.study.network.tcp.examples.ex04;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* @Name: ImageUploadServer
* @Description: 案例四：文件上传服务端
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-1-12 下午10:08:27 
* @Version: V1.0
 */
public class ImageUploadServer {
	
	public static void main(String[] args) throws IOException {
		//创建服务端Socket对象
		ServerSocket server = new ServerSocket(12345) ;
		System.out.println("启动图片上传服务器...");
		//监听客户端连接
		Socket socket = server.accept() ;
		//获取输入字节流，并包装成高效输入字节流对象
		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()) ;
		//创建文件输出字节流，并包装成高效输出字节流对象
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("upload.jpg")) ;
		//将客户端文件上传到当前目录下的upload.jpg
		byte[] buf = new byte[1024] ;
		int len = 0 ;
		while((len = bis.read(buf)) != -1) {
			bos.write(buf, 0, len) ;
			bos.flush() ;
		}
		//向客户端反馈上传状态
		OutputStream os = socket.getOutputStream() ;
		String status = "上传成功!" ;
		os.write(status.getBytes()) ;
		bos.close() ;
		socket.close() ;
	}

}
